<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>绘制单通道图片-图片链接</title>
		<style type="text/css">
			.imga{
				width: 160px;
				height: 160px;
				border: #A9A9A9 solid 1px;
			}
		</style>
	</head>
	<body>
		
		<div>
			<h2>该案例是实现单通道资源图片的展示，例如ir图或深度图，不是正常的rgba图片在极速模式下的浏览器无法显示的问题。</h2>
			<h6>实现方式是获取一个<i>单通道图片的链接</i>，获取该图片的内容信息后补齐其他通道值再重新绘制到画布上的做法。</h6>
			<h6>涉及文件：当前文本和一个单通道图片</h6>
			<img src="depth_0.bmp" id="sid" class="imga" alt="图片不显示" />
			<canvas id="canvas" width="160" height="160"></canvas>
		</div>
		
		<script type="text/javascript">
			var BASE64_MARKER = ';base64,';
			var pic = document.getElementById('sid');
			preView(pic.src);
			function preView(url){
				console.log('start', new Date().getTime().toString());
			    let reader    = new FileReader();
			
			    getImageBlob( url , function(blob){
			        reader.readAsDataURL(blob);
			    });
			
			    reader.onload = function(e) {
					var data = convertDataURIToBinary(e.target.result);
					canvasImg(data);
			    }
			}
			
			// 根据URL获取图片的Blob对象
			function getImageBlob(url, cb) {
			    var xhr = new XMLHttpRequest();
				xhr.open("get", url, true);
				xhr.responseType = "blob";
				xhr.onload = function() {
					if (this.status == 200) {
						if(cb) cb(this.response);
					}
				};
				xhr.send();
			};
			
			// 将base64 转 Uint8Array
			function convertDataURIToBinary(dataURI) {
			  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
			  var base64 = dataURI.substring(base64Index);
			  var raw = window.atob(base64);
			  var rawLength = raw.length;
			  var array = new Uint8Array(new ArrayBuffer(rawLength));
			
			  for(i = 0; i < rawLength; i++) {
			    array[i] = raw.charCodeAt(i);
			  }
			  console.log(array)
			  return array;
			}
			
			// 绘制到画布上
			function canvasImg(data) {
				var canvas = document.getElementById("canvas");
				var ctx = canvas.getContext("2d");
				
				let img_w = data[18] + data[19] * 256 + data[20] * 1024 + data[21] * 2048;
				let img_h = data[22] + data[23] * 256 + data[24] * 1024 + data[25] * 2048;
				
				ctx.drawImage(pic, 0, 0, img_w, img_h);
				var pixels = ctx.getImageData(0, 0, img_w, img_h);
				var line = 0;
				let rgb_un8 = new Uint8Array(img_w * img_h);
				for (let idx = img_h - 1; idx >= 0; idx--) {
					for (let idy = 0; idy < img_w; idy++) {
						rgb_un8[idx * img_w + idy] = data[1078 + line * img_w + idy]
					}
					line++
				}
				for (var i = 0, j = 0; j < rgb_un8.length; j++, i += 4) {
					pixels.data[i] = rgb_un8[j]
					pixels.data[i + 1] = rgb_un8[j]
					pixels.data[i + 2] = rgb_un8[j]
					pixels.data[i + 3] = 255
				}
				ctx.putImageData(pixels, 0, 0);
				console.log('end', new Date().getTime().toString());
			}
		</script>
	</body>
</html>
